﻿#include "g711decoder.h"
#include "udpplay.h"
#include "g711encoder.h"

UDPPlay::UDPPlay(quint16 port, QObject *parent)
    :QObject(parent),listenPort(port)
{
    recvSocket = new QUdpSocket();
    recvSocket->bind(listenPort);
    //QAudioFormat format;
    format.setSampleRate(8000);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setCodec("audio/g711a");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);

    QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
    if (!info.isFormatSupported(format)){
        qWarning() << "Default format not supported, trying to use the nearest.";
        format = info.nearestFormat(format);  
     }


}

void UDPPlay::playData()
{
    //You need to read datagrams from the udp socket
    while (recvSocket->hasPendingDatagrams())
    {
        QByteArray data;
        data.resize(recvSocket->pendingDatagramSize());
        recvSocket->readDatagram(data.data(), data.size());
        qDebug()<<"playData的大小 "+ QString::number(data.size());

        QByteArray decodedData;
        decodedData.resize(data.size() * sizeof(int16_t));
        int16_t *pcmSamples = reinterpret_cast<int16_t*>(decodedData.data());
        for (int i = 0; i < data.size(); ++i) {
            pcmSamples[i] =  G711Encoder::alaw2linear(static_cast<uint8_t>(data[i]));
            qDebug() << "A-law Encoded:" << data[i] << "pcm:" << pcmSamples[i];
        }
        qDebug()<<"decodedData的大小 "+ QString::number(decodedData.size());
//        其他处理
        playDevice->write(decodedData.data(), decodedData.size());

    }
}

void UDPPlay::startPlay()
{
    audioOutput = new QAudioOutput(format);

    playDevice = audioOutput->start();
    connect(recvSocket, SIGNAL(readyRead()), this, SLOT(playData()));

    qDebug()<<"startPlay"<<audioOutput<<playDevice;
}

void UDPPlay::stopPlay()
{
    qDebug()<<"stopPlay"<<audioOutput<<playDevice;
    audioOutput->stop();
    audioOutput->disconnect();


//    recvSocket->disconnect();
//    playDevice->reset();
//    playDevice->disconnect();
//    playDevice->close();

    delete audioOutput;
//    delete playDevice;
    qDebug()<<"stopPlay2"<<audioOutput<<playDevice;

    audioOutput = nullptr;
//    playDevice = nullptr;
    qDebug()<<"stopPlay3"<<audioOutput<<playDevice;
}


